<template>
  <van-form>
    <van-cell-group inset>
      <van-field
        v-model="formData.name"
        name="name"
        label="用户名"
        left-icon="user-o"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="formData.phone"
        name="phone"
        label="手机号码"
        left-icon="phone-o"
        placeholder="手机号码"
        :rules="[{ required: true, message: '请填写手机号码' }]"
      />
      <van-field
        v-model="formData.password"
        type="password"
        name="password"
        label="密码"
        left-icon="shield-o"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button
        round
        block
        type="primary"
        @click="switchLoginOrRegister(props.type)()"
      >
        {{ btnTxt }}
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { showToast } from 'vant';
import 'vant/es/toast/style';
import { useRouter } from 'vue-router';
import useUserStore from '@/stores/user';
//type为1表示登录，type为2表示注册
const props = defineProps({
  type: {
    default: 1,
  },
});
const btnTxt = ref('登录');
const userStore = useUserStore();
const router = useRouter();
//处理按钮文本
const switchBtnTxt = (type) => {
  const obj = {
    1: () => {
      btnTxt.value = '登录';
    },
    2: () => {
      btnTxt.value = '注册';
    },
  };
  return obj[type];
};
//处理登录/注册
const switchLoginOrRegister = (type) => {
  const obj = {
    1: () => {
      userStore.userLogin(formData);
      showToast({
        message: '登录成功,即将返回',
        icon: 'success',
        color: '#1989fa',
        onClose: () => {
          router.push('/');
        },
      });
    },
    2: () => {
      userStore.userRegister(formData);
      showToast({
        message: '注册成功，快去登录吧',
        color: '#1989fa',
      });
    },
  };
  return obj[type];
};
//表单数据
const formData = reactive({
  name: 'jay',
  phone: '18000000000',
  password: '666',
  project_id: 2,
});

onMounted(() => {
  switchBtnTxt(props.type)();
});
</script>

<style lang="scss" scoped></style>
